package com.i2works.smartluolong.web.service.company.impl;

import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.CompanyStatusEnum;
import com.i2works.smartluolong.utils.base.FlowItemTypeEnum;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.utils.redis.RedisSessionDAO;
import com.i2works.smartluolong.web.dal.company.dao.ICompanyApplyMemberDAO;
import com.i2works.smartluolong.web.entity.common.HoliDayQuery;
import com.i2works.smartluolong.web.entity.company.CompanyApplyDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyMemberDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyMemberQuery;
import com.i2works.smartluolong.web.entity.company.CompanyApplyQuery;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.items.ItemsDO;
import com.i2works.smartluolong.web.entity.items.ItemsQuery;
import com.i2works.smartluolong.web.entity.user.UserAccountDO;
import com.i2works.smartluolong.web.service.common.IHolidayService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyMemberService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.items.IItemsService;
import com.xiaoleilu.hutool.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 工商申请业务实现类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/14 16:42
 */

@Service("companyApplyMemberService")
public class CompanyApplyMemberServiceImpl extends BaseCommonServiceImpl<CompanyApplyMemberQuery, CompanyApplyMemberDO> implements ICompanyApplyMemberService {


    private final ICompanyApplyMemberDAO companyApplyMemberDAO;
    private final ICompanyApplyService companyApplyService;
    private final IFlowInfoService flowInfoService;
    private final IHolidayService holidayService;
    private final RedisSessionDAO redisSessionDAO;
    private final IItemsService itemsService;

    @Autowired
    public CompanyApplyMemberServiceImpl(IHolidayService holidayService, RedisSessionDAO redisSessionDAO, IItemsService itemsService, IFlowInfoService flowInfoService, ICompanyApplyMemberDAO companyApplyMemberDAO, ICompanyApplyService companyApplyService) {
        this.holidayService = holidayService;
        this.redisSessionDAO = redisSessionDAO;
        this.itemsService = itemsService;
        this.flowInfoService = flowInfoService;
        this.companyApplyMemberDAO = companyApplyMemberDAO;
        this.companyApplyService = companyApplyService;
    }


    /**
     * 后台查询股东信息（返回股东身份）
     */
    @Override
    public List<CompanyApplyMemberDO> queryShareHolderList(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            return companyApplyMemberDAO.queryShareHolderList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 保存人员（根据姓名、证件号、申请ID、身份ID来判断当前人是否存在，存在就更新，不存在就新增）
     *
     * @param companyApplyMemberDO 人员实体
     * @param companyApply         工商信息实体
     * @param isLast               是否最后一步
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void saveMember(CompanyApplyMemberDO companyApplyMember, CompanyApplyDO companyApply, Boolean isLast) throws ServiceException {
        CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
        memberQuery.setApplyId(companyApplyMember.getApplyId());
        memberQuery.setIdentity(companyApplyMember.getIdentity());
        try {
            String flowInfoMessage;
            CompanyApplyMemberDO resultCompanyApplyMember = companyApplyMemberDAO.query(memberQuery);
            if (null != resultCompanyApplyMember) {
                companyApplyMember.setId(resultCompanyApplyMember.getId());
                companyApplyMemberDAO.update(companyApplyMember);
            } else {
                companyApplyMember.setCreateName(companyApplyMember.getUpdateName());
                companyApplyMemberDAO.save(companyApplyMember);
            }
            if (isLast) {
                //更新主表状态
                CompanyApplyDO updateCompanyApply = new CompanyApplyDO();
                updateCompanyApply.setId(companyApply.getId());
                updateCompanyApply.setApplyStatus(CompanyStatusEnum.STATUS_10.getKey());
                updateCompanyApply.setUpdateName(companyApplyMember.getUpdateName());
                companyApplyService.update(updateCompanyApply);
                //添加工作流
                FlowInfoDO flowInfoDO = new FlowInfoDO();
                flowInfoDO.setItemId(companyApply.getId());
                flowInfoDO.setComplete(0);
                flowInfoDO.setItemName(companyApply.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
                flowInfoDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
                flowInfoDO.setItemStatus(CompanyStatusEnum.STATUS_10.getKey());
                flowInfoDO.setUserId(companyApply.getUserId());
                flowInfoDO.setUpdateName(companyApplyMember.getUpdateName());
                flowInfoDO.setMessage("用户《" + flowInfoDO.getUpdateName() + "》提交资料，待补充自拍照和个人签名。");
                //添加事项期限的级别和时间
                flowInfoDO.setTermLevel(GlobalConstant.termLevel.L1);
                flowInfoDO.setDeadline(getDeadline(FlowItemTypeEnum.COMPANY_APPLY.getKey()));
                flowInfoService.save(flowInfoDO);
            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 保存和更新（根据对象ID判断）
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void saveOrUpdate(CompanyApplyMemberDO companyApplyMemberDO) throws ServiceException {
        try {
            if (companyApplyMemberDO.getId() != null) {
                companyApplyMemberDAO.update(companyApplyMemberDO);
            } else {
                companyApplyMemberDO.setCreateName(companyApplyMemberDO.getUpdateName());
                companyApplyMemberDAO.save(companyApplyMemberDO);
            }

        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 手机端更新股东、法人、代办人自拍
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void updateSupplement(List<CompanyApplyMemberDO> memeberList, UserAccountDO userAccount) throws ServiceException {
        try {
            Integer applyId = null;
            for (CompanyApplyMemberDO memberDO : memeberList) {
                applyId = memberDO.getApplyId();
                //获取name，applyId一样的用户
                CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
                memberQuery.setApplyId(memberDO.getApplyId());
                memberQuery.setName(memberDO.getName());
                List<CompanyApplyMemberDO> asMemberList = companyApplyMemberDAO.queryList(memberQuery);
                if (CollUtil.isNotEmpty(asMemberList)) {
                    for (CompanyApplyMemberDO applyMemberDO : asMemberList) {
                        applyMemberDO.setAutograph(memberDO.getAutograph());
                        applyMemberDO.setSelfie(memberDO.getSelfie());
                        companyApplyMemberDAO.update(applyMemberDO);
                    }
                }
            }

            //更新申请状态(待审核)
            CompanyApplyDO companyApplyDO = new CompanyApplyDO();
            companyApplyDO.setId(applyId);
            companyApplyDO.setApplyStatus(CompanyStatusEnum.STATUS_1.getKey());
            companyApplyService.update(companyApplyDO);
            CompanyApplyQuery companyApplyQuery = new CompanyApplyQuery();
            companyApplyQuery.setId(applyId);
            CompanyApplyDO companyApply = companyApplyService.query(companyApplyQuery);

            //添加工作流
            FlowInfoDO flowInfoDO = new FlowInfoDO();
            flowInfoDO.setItemId(companyApply.getId());
            flowInfoDO.setComplete(0);
            flowInfoDO.setItemName(companyApply.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
            flowInfoDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
            flowInfoDO.setItemStatus(CompanyStatusEnum.STATUS_1.getKey());
            flowInfoDO.setUserId(userAccount.getId());
            flowInfoDO.setUpdateName(userAccount.getUserName());
            flowInfoDO.setMessage("用户《" + flowInfoDO.getUpdateName() + "》提交审核");
            flowInfoService.save(flowInfoDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 删除（根据applyId,角色，身份）
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void deleteByItemParam(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            companyApplyMemberDAO.deleteByItemParam(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 根据applyId + user.role 删除股东信息
     */
    @Override
    public void deleteShareholderByRole(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            companyApplyMemberDAO.deleteShareholderByRole(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取事项到期日期
     */
    private Date getDeadline(String itemType) throws ServiceException {
        List<String> dateList = Lists.newArrayList();
        //查询节假日列表
        String dateListTags = GlobalConstant.redis.DATE_LIST_TAGS;
        List list = redisSessionDAO.get(dateListTags, List.class);
        if (CollUtil.isNotEmpty(list)) {
            dateList.addAll(list);
        } else {
            List<String> allDateList = holidayService.queryAll(new HoliDayQuery());
            redisSessionDAO.set(dateListTags, allDateList);
            dateList.addAll(allDateList);
        }
        //查询天数
        ItemsQuery itemsQuery = new ItemsQuery();
        itemsQuery.setItemType(itemType);
        ItemsDO itemsDO = itemsService.query(itemsQuery);
        Date workday;
        if (itemsDO != null) {
            workday = BaseUtils.workday(dateList, new Date(), itemsDO.getPromiseTerm(), false);
        } else {
            workday = BaseUtils.workday(dateList, new Date(), 5, false);
        }
        return workday;
    }

    /**
     * 后台查询股东/法人/代办人信息
     *
     * @param query    查询参数
     * @param distinct 是否去重
     */
    @Override
    public List<CompanyApplyMemberDO> queryComplementMemberList(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            return companyApplyMemberDAO.queryComplementMemberList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 后台查询董事、监事、经理信息
     *
     * @param query    查询参数
     * @param distinct 是否去重
     */
    @Override
    @Deprecated
    public List<CompanyApplyMemberDO> querySupervisorMemberList(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            return companyApplyMemberDAO.querySupervisorMemberList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 查询短信通知人的电话列表（法人和代办人）
     */
    @Override
    public Set<String> querySmsList(CompanyApplyMemberQuery query) throws ServiceException {
        try {
            return companyApplyMemberDAO.querySmsList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }
}
